# python 3.8
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
from conf.operactionconfig import OperactionConfig


def get_decode():
    """
    生成钉钉签名的函数
    
    Args:
        无参数
    
    Returns:
        tuple: 包含两个元素的元组，分别为：
            - timestamp (str): 当前时间戳，单位为毫秒
            - sign (str): 钉钉签名，用于请求钉钉接口时验证请求来源
    
    """
    timestamp = str(round(time.time() * 1000))
    secret = OperactionConfig().get_section_for_data('Dingtalk', 'secret')
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign


def sendmsg(content, at_all=True):
    """
    向钉钉群机器人发送文本消息
    
    Args:
        content (str): 要发送的文本内容
        at_all (bool, optional): 是否@所有人，默认为True
    
    Returns:
        requests.Response: 发送请求后返回的响应对象
    
    """
    urldata = get_decode()

    print(urldata[0], urldata[1])
    url = f'https://oapi.dingtalk.com/robot/send?access_token=ec79ec620cdda654824f3b0833d3bf41f192c87af78c8792c66074891ffce9e6&timestamp={urldata[0]}&sign={urldata[1]}'
    data = {
        'msgtype': 'text',
        'text': {
            'content': content
        },
        'at': {
            'isAtAll': at_all
        }
    }
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    return requests.post(url=url, json=data, headers=headers)


